package com.hobobe.tiercel.server.filter;

import java.net.SocketAddress;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.frame.FrameDecoder;

import com.hobobe.tiercel.ProtocolUtil;
import com.hobobe.tiercel.XLCharSetFactory;
import com.hobobe.tiercel.XLResponse;
import com.hobobe.tiercel.server.handler.TcpResponse;

public class ServerDecoder extends FrameDecoder {
	@Override
    protected Object decode(ChannelHandlerContext context, Channel channel, ChannelBuffer buffer) throws Exception {
        if (buffer.readableBytes()<16) {
            return null;
        }
        buffer.markReaderIndex();
        byte encode=buffer.readByte();
        byte encrypt=buffer.readByte();
        byte command=buffer.readByte();
        byte extend1=buffer.readByte();
        byte extend2=buffer.readByte();
        int sessionid=buffer.readInt();
        int result=buffer.readInt();
        int length=buffer.readInt(); // 数据包长
        if (buffer.readableBytes()<length) {
            buffer.resetReaderIndex();
            return null;
        }
        ChannelBuffer dataBuffer=ChannelBuffers.buffer(length);
        buffer.readBytes(dataBuffer, length);
        
        TcpResponse response=new TcpResponse();
        response.setEncode(encode);
        response.setEncrypt(encrypt);
        response.setEncrypt(command);
        response.setExtend1(extend1);
        response.setExtend2(extend2);
        response.setSessionid(sessionid);
        response.setResult(result);
        response.setLength(length);
//        response.setValues(ProtocolUtil.decode(encode, dataBuffer));
        response.setData(decode(encode,dataBuffer));
        response.setIp(getClientIp(channel));
        return response;
    }
	
	  /**
     * 解码报文的数据部分
     * @param encode
     * @param dataBuffer
     * @return
     */
    public  byte[] decode(int encode,ChannelBuffer dataBuffer){
        Map<String,String> dataMap=new HashMap<String, String>();
       if (dataBuffer!=null && dataBuffer.readableBytes()>0) {
            int processIndex=0,length=dataBuffer.readableBytes();
            Charset charset=XLCharSetFactory.getCharset(encode);
            while(processIndex<length){
                /**
                * 获取Key
                */
               int size=dataBuffer.readInt();
               byte [] contents=new byte [size];
               dataBuffer.readBytes(contents);
               String key=new String(contents, charset);
               processIndex=processIndex+size+4;
               /**
                 * 获取Value
                 */
               size=dataBuffer.readInt();
               contents=new byte [size];
               dataBuffer.readBytes(contents);
               String value=new String(contents, charset);
               dataMap.put(key, value);
               processIndex=processIndex+size+4;
           }
       }
       return dataMap;
    }
  
   /**
     * 获取客户端IP
    * @param channel
     * @return
     */
    public  String getClientIp(Channel channel){
       /**
        * 获取客户端IP
        */
        SocketAddress address = channel.getRemoteAddress();
       String ip = "";
       if (address != null) {
            ip = address.toString().trim();
            int index = ip.lastIndexOf(':');
           if (index < 1) {
                index = ip.length();
            }
           ip = ip.substring(1, index);
        }
       if (ip.length() > 15) {
            ip = ip.substring(Math.max(ip.indexOf("/") + 1, ip.length() - 15));
        }
        return ip;
    }
}
